<template>
  <div class="browserView">
    <!-- 页签栏 -->
    <div class="tab-bar">
      <!-- 页签列表 -->
      <div class="tab-list" ref="tabListRef">
        <div
          v-for="tab in tabs"
          :key="tab.id"
          class="tab"
          :class="{
            active: tab.isActive,
            'ai-tab': tab.isAI,
            draggable: !tab.isAI
          }"
          @click="switchTab(tab.id)"
        >
          <!-- :draggable="!tab.isAI"
          @dragstart="handleDragStart($event, tab)"
          @dragover="handleDragOver($event)"
          @drop="handleDrop($event, tab)" -->

          <!-- 页签图标 -->
          <div class="tab-icon">
             <img v-if="tab.isAI" :src="aiAssistantIcon" :width="20"></img>
             <img v-if="tab.id === 'settings'" :src="currentCenterIcon" :width="20"></img>
          </div>

          <!-- 页签标题 -->
          <div class="tab-title">
            <span v-if="tab.id === 'ai-tab'">{{ $t('browserView.QandA') }}</span>
            <span v-else-if="tab.id === 'settings'">{{ $t('browserView.aiSettings') }}</span>
            <span v-else>{{ tab.title || $t('browserView.newTab')}}</span>
          </div>

          <!-- 关闭按钮 (非AI页签) -->
          <div v-if="!tab.isAI" class="tab-close" @click.stop="closeTab(tab.id)">
            <el-icon><Close /></el-icon>
          </div>
        </div>
      </div>
      <!-- 页签栏拖动区域 -->
      <!-- <div class="drag-box" @mousedown.self="handleMouseDown"></div> -->
      <div class="drag-box">
        <!-- 添加新页签按钮 -->
        <div class="add-tab" @click="createNewTab()">
          <span>+</span>
        </div>
        <div class="drag-area"></div>
      </div>

      <!-- 页签栏操作按钮 -->
      <div class="tab-bar-actions">
        <div @click="minWin">
          <el-icon><SemiSelect /></el-icon>
        </div>
        <div @click="maxWin">
          <img v-if="isMaximized" :src="maximize" alt="" width="15">
          <img v-else :src="minimize" alt="" width="20">
          <!-- <el-icon v-if="isMaximized"><FullScreen /></el-icon> -->
          <!-- <el-icon v-else><CloseBold /></el-icon> -->
        </div>
        <div @click="winClose">
          <el-icon><CloseBold /></el-icon>
        </div>
      </div>
    </div>

    <!-- 导航栏 -->
    <div class="nav-bar" v-if="activeTab && activeTab.id != 'ai-tab' && activeTab.id != 'settings'">
      <div class="nav-buttons">
        <!-- 后退 -->
        <el-button circle link @click="goBack(activeTab.id)" :disabled="!navState.canGoBack" v-if="false">
          <el-icon class="nav-icon" :class="{'nav-icon-disabled': !navState.canGoBack}"><ArrowLeft /></el-icon>
        </el-button>
        <!-- 前进 -->
        <el-button circle link  @click="goForward(activeTab.id)" :disabled="!navState.canGoForward" v-if="false">
          <el-icon class="nav-icon" :class="{'nav-icon-disabled': !navState.canGoForward}"><ArrowRight /></el-icon>
        </el-button>
        <!-- 刷新 -->
        <el-button circle link  @click="reload(activeTab.id)" :disabled="!activeTab.url || reloadState">
          <el-icon class="nav-icon" :class="{ spinning: isSpinning, 'nav-icon-disabled': !activeTab.url || reloadState }"><RefreshRight /></el-icon>
        </el-button>
      </div>
      <!-- 地址栏 -->
      <div class="address-bar">
        <input
          type="text"
          v-model="currentUrl"
          @keyup.enter="navigateToUrl(activeTab.id, currentUrl)"
          :placeholder="$t('browserView.enterUrl')"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, onBeforeUnmount, nextTick } from 'vue'
import ipcMainApi from '@/ipcMainApi'
import {
  Close,
  ArrowLeft,
  ArrowRight,
  RefreshRight,
  SemiSelect,
  CloseBold
} from '@element-plus/icons-vue'

const aiAssistantIcon = ref(new URL('@/assets/image/aiAssistant/aiAssistant.png', import.meta.url).href)
const currentCenterIcon = ref(new URL('@/assets/image/aiAssistant/currentCenter.png', import.meta.url).href)
const maximize = ref(new URL('@/assets/image/aiAssistant/maximize.png', import.meta.url).href)
const minimize = ref(new URL('@/assets/image/aiAssistant/minimize.png', import.meta.url).href)

//最小化
const minWin = () => {
  ipcMainApi.browserViewApi.minBrowserView()
}

//最大化
const maxWin = () => {
  ipcMainApi.browserViewApi.maxBrowserView()
}

// 关闭窗口
const winClose = () => {
  ipcMainApi.browserViewApi.hideBrowserView()
}

const tabListRef = ref<HTMLElement | null>(null)

// 将垂直滚轮转为横向滚动，支持触控板原生横向滚动
const handleTabListWheel = (e: WheelEvent) => {
  const el = tabListRef.value
  if (!el) return

  // 取横向/纵向中更明显的方向作为主滚动轴
  const absX = Math.abs(e.deltaX)
  const absY = Math.abs(e.deltaY)
  const primary = absX > absY ? e.deltaX : e.deltaY
  if (primary === 0) return

  // 阻止默认垂直滚动，改为横向滚动
  e.preventDefault()

  // 调整滚动灵敏度（可按需微调）
  const factor = 1
  el.scrollBy({ left: primary * factor, behavior: 'smooth' })
}

// 页签数据
interface Tab {
  id: string
  title: string
  url: string
  isAI: boolean
  isActive: boolean
}

const tabs = ref<Tab[]>([])
const currentUrl = ref('')

// 当前活动页签
const activeTab = computed(() => {
  return tabs.value.find((tab) => tab.isActive)
})

// 监听活动页签变化，更新地址栏
watch(activeTab, (newTab) => {
  if (newTab) {
    currentUrl.value = newTab.url
  } else {
    currentUrl.value = ''
  }
})

// 页签拖拽相关
// let draggedTab: Tab | null = null
// function handleDragStart(event: DragEvent, tab: Tab) {
  
//   if (tab.isAI) { // 只允许非AI页签拖拽
//     event.preventDefault()
//     return
//   }

//   draggedTab = tab
// }

// function handleDragOver(event: DragEvent) {
//   event.preventDefault()
// }

// function handleDrop(event: DragEvent, targetTab: Tab) {
//   event.preventDefault()
//   // 不允许拖拽到AI页签前面
//   if (!draggedTab || targetTab.isAI) {
//     return
//   }
//   // 重新排序页签
//   const updatedTabs = [...tabs.value]
//   const draggedIndex = updatedTabs.findIndex((tab) => tab.id === draggedTab!.id)
//   const targetIndex = updatedTabs.findIndex((tab) => tab.id === targetTab.id)

//   if (draggedIndex !== -1 && targetIndex !== -1) {
//     // 移除拖拽的页签
//     const [draggedTabItem] = updatedTabs.splice(draggedIndex, 1)
//     // 插入到目标位置
//     updatedTabs.splice(targetIndex, 0, draggedTabItem)
//     // 更新页签顺序
//     tabs.value = updatedTabs
//   }
//   draggedTab = null
// }

// 滚动到最右侧，使用 smooth 动画
const scrollTabListToRight = () => {
  const el = tabListRef.value
  if (!el) return
  el.scrollTo({ left: el.scrollWidth, behavior: 'smooth' })
}

// 创建新页签
async function createNewTab(url?: string) {
  try {
    await ipcMainApi.browserViewApi.createTab(url)

    await nextTick()
    // 再等一帧，确保布局完成后再滚动（避免滚动距离不够）
    requestAnimationFrame(() => {
      scrollTabListToRight()
    })
  } catch (error) {
    console.error('创建页签失败:', error)
  }
}

// 关闭页签
async function closeTab(tabId: string) {
  try {
    await ipcMainApi.browserViewApi.closeTab(tabId)
  } catch (error) {
    console.error('关闭页签失败:', error)
  }
}

// 切换页签
async function switchTab(tabId: string) {
  try {
    await ipcMainApi.browserViewApi.switchTab(tabId)
    navState.value = await ipcMainApi.browserViewApi.getNavState(tabId)
  } catch (error) {
    console.error('切换页签失败:', error)
  }
}

// 导航到URL
async function navigateToUrl(tabId: string, url: string) {
  // 如果URL不包含协议，添加https://
  if (url && !url.startsWith('http://') && !url.startsWith('https://')) {
    url = 'https://' + url
  }
  try {
    await ipcMainApi.browserViewApi.navigateTo(tabId, url)
    currentUrl.value = url
  } catch (error) {
    console.error('导航失败:', error)
  }
}

const isSpinning = ref(false)
const reloadState = ref(false)
const navState = ref({
  canGoBack: false,
  canGoForward: false
})

// 页面后退
async function goBack(tabId: string) {
  try {
    await ipcMainApi.browserViewApi.goBack(tabId)
    navState.value = await ipcMainApi.browserViewApi.getNavState(tabId)
  } catch (error) {
    console.error('后退失败:', error)
  }
}

// 页面前进
async function goForward(tabId: string) {
  try {
    await ipcMainApi.browserViewApi.goForward(tabId)
    navState.value =  await ipcMainApi.browserViewApi.getNavState(tabId)
  } catch (error) {
    console.error('前进失败:', error)
  }
}

// 刷新页面
async function reload(tabId: string) {
  try {
    isSpinning.value = true
    reloadState.value = true
    setTimeout(() => {
      isSpinning.value = false
      reloadState.value = false
    }, 1500)
    await ipcMainApi.browserViewApi.reload(tabId)
  } catch (error) {
    console.error('刷新失败:', error)
  }
}

const isMaximized = ref(false)

// 监听页签更新事件
onMounted(async () => {
  // 监听主进程发送的页签更新事件
  window.electron.ipcRenderer.on('update-tabs', (_event, updatedTabs: Tab[]) => {
    tabs.value = updatedTabs
    // 更新当前URL和导航状态
    const currentActiveTab = updatedTabs.find((tab) => tab.isActive)
    if (currentActiveTab) {
      currentUrl.value = currentActiveTab.url
    }
  })
  window.electron.ipcRenderer.on('browserView-isMaximized', (_event, val: boolean) => {
    isMaximized.value = val
  })

  // 首次加载时获取页签数据
  tabs.value = await ipcMainApi.browserViewApi.getBrowserTabs()

  // 页签滚动
  const el = tabListRef.value
  if (el) {
    // passive: false 以便在回调里调用 preventDefault()
    el.addEventListener('wheel', handleTabListWheel, { passive: false })
  }
})

onBeforeUnmount(() => {
  const el = tabListRef.value
  if (el) {
    el.removeEventListener('wheel', handleTabListWheel as EventListener)
  }
})
</script>

<style lang="scss" scoped>
.browserView {
  height: 100vh;
  display: flex;
  flex-direction: column;
  user-select: none; /* 不允许鼠标复制 */
  .tab-bar {
    display: flex;
    justify-content: space-between;
    height: 40px;
    background-color: #131313;
    // 页签列表：自适应宽度 + 最大宽度限制 + 隐藏滚动条
    .tab-list {
      display: flex;
      flex: 0 1 auto;            // 根据内容宽度自适应，不强行占满
      min-width: 0;              // 允许在空间不足时收缩
      max-width: calc(100vw - 250px); // 限制最大宽度（扣除右侧操作区）
      white-space: nowrap;
      overflow-x: auto;          // 超出时横向滚动
      overflow-y: hidden;
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;     // Firefox 隐藏滚动条
      -ms-overflow-style: none;  // IE/Edge 隐藏滚动条

      &::-webkit-scrollbar {     // WebKit 隐藏滚动条
        display: none;
        height: 0;
      }
      // 页签项保持原有视觉（如需可继续微调）
      .tab {
        display: flex;
        align-items: center;
        min-width: 120px;
        max-width: 200px;
        height: 100%;
        padding: 0 8px;
        background-color: #131313;
        color: #959595;
        cursor: pointer;
        transition: background-color 0.2s;
        border-right: 1px solid #333;
        &.ai-tab {
          justify-content: center;
          .tab-title {
            flex: none;
          }
        }
        &:hover {
          background-color: #262626;
        }
        &.active {
          background-color: #333;
          color: #dfdfdf;
        }
        .tab-icon {
          margin-right: 6px;
        }
        .tab-title {
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 13px;
        }
        .tab-close {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 16px;
          height: 16px;
          margin-left: 6px;
          border-radius: 50%;
          font-size: 14px;
          color: #666;
          &:hover {
            color: #dfdfdf;
          }
        }
      }

      
    }

    // 拖动区域：自动扩展占满剩余空间
    .drag-box {
      flex: 1 1 auto;
      height: 100%;
      display: flex;
      .add-tab {
        display: flex;
        align-items: center;
        justify-content: center;
        min-width: 40px;
        width: 40px;
        height: 100%;
        background-color: #131313;
        cursor: pointer;
        font-size: 20px;
        font-weight: bold;
        color: #959595;
        &:hover {
          background-color: #262626;
        }
      }
      .drag-area {
        flex: 1;
        height: 100%;
        -webkit-app-region: drag;
      }
    }

    // 操作按钮区域：固定宽度
    .tab-bar-actions {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 100%;
      color: #959595;
      flex: 0 0 150px;
      width: 150px;
      > div {
        cursor: pointer;
        height: 100%;
        width: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        &:hover {
          // color: #dfdfdf;
          background-color: #262626;
        }
      }
    }
  }

  // 响应式：适配较窄窗口时的单个标签宽度
  @media (max-width: 1024px) {
    .tab-bar .tab-list .tab {
      min-width: 100px;
      max-width: 180px;
    }
  }
  @media (max-width: 768px) {
    .tab-bar .tab-list .tab {
      min-width: 90px;
      max-width: 160px;
    }
  }
  .nav-bar {
    display: flex;
    height: 50px;
    padding: 0 8px;
    background-color: #333;
    .nav-buttons {
      display: flex;
      align-items: center;
      padding-left: 8px;
      padding-right: 5px;
      .nav-icon {
        font-size: 18px;
        color: #ccc;
        margin-right: 10px;
        &:hover {
          color: #fff;
        }
        &.nav-icon-disabled {
          color: #666;
          &:hover {
            color: #666;
          }
        }
        &.spinning {
          animation: spin 0.5s linear;
        }

        @keyframes spin {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
      }
    }

    .address-bar {
      flex: 1;
      display: flex;
      align-items: center;
      input {
        width: 100%;
        height: 30px;
        padding: 0 15px;
        border-radius: 15px;
        font-size: 14px;
        color: #e3e3e3;
        background-color: #131313;
        border: 1px solid #131313;
        &:focus {
          outline: none;
          border: solid 1px #2196f3;
        }
      }
    }
  }
}
</style>
